package
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.ColorTransform;
	import flash.utils.Timer;
	
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Button;
	import mx.controls.Label;
	
	public class GenerateTable extends EventDispatcher
	{
		private var btn81:Array;
		public var service:ServiceFunctions;
		private var colouredBtn:ColorTransform;
		

		private var timeR:Timer;
		
		public var now:int;

		[Bindable]
		static public var iTimeLab:Label;
		
		private var iTableCnt:HBox;
		
		public function onTimer(e:TimerEvent):void
		{

			trace("ENTER:onTimer()");
			trace(now);
		    now++;
			trace(hasEventListener(DataEventHandle.DATA_EVENT));
			dispatchEvent(new Event("getScore"));
		    

			var sec:int = timeR.currentCount;
			var min:int = timeR.currentCount;
			sec = sec % 60;
			min = min/60;
			
			if (min < 10 )
			{
				iTimeLab.text = '0';
			}
			iTimeLab.text += min.toString();
			iTimeLab.text += ':';
			if (sec < 10)
			{
				iTimeLab.text +='0';
			}
			iTimeLab.text+=sec.toString();

			trace("EXIT:onTimer()");
		}
		
		public function TimerReset():void
		{
			timeR.reset();
		}
		public function TimerStop():void
		{
			timeR.stop();
		}
		public function TimerResume():void
		{
			timeR.start();
		}
		
		public function GenerateTable(s:ServiceFunctions)
		{	
			timeR = new Timer(1000,0)
			iTimeLab = new Label();
			iTimeLab.text = '00:00';
			service = s;

			var temp:Button = new Button();
			colouredBtn = temp.transform.colorTransform;

		}
		
		public function checkIfPossible(event:MouseEvent):Boolean 
		{	
			trace("ENTER:checkIfPossible()");

			//trace(hasEventListener(DataEventHandle.DATA_EVENT));
			//dispatchEvent(new DataEventHandle(DataEventHandle.DATA_EVENT, now));

			if (!parseInt( Button( event.target ).label ))
			{
				return true;
			}
		
			var currLabel:String = Button( event.target ).label;
			var currId:int = parseInt( Button( event.target ).id );
			var currColumn:int = currId / 9;
			var ind:int = currId;
			var cnt:int = 0;
			
			//horizontal check
			//trace("Index");
			for (;cnt < 8; cnt++)
			{
				ind = (ind + 9) % 81;
				
				//trace(ind);
				if (btn81[ind].label == currLabel && currId != parseInt( btn81[ind].id ))
				{
					//Alert.show("Busy row");
					return false;
				}
			}
			//horizontal check

			//vertical check			
			cnt = currColumn*9;
			for (; cnt < (currColumn + 1) * 9 ; cnt++)
			{
				if (btn81[cnt].label == currLabel && currId != parseInt( btn81[cnt].id ))
				{
					//Alert.show("Busy column");
					return false;
				}
			}
			//vertical check
			
			trace("EXIT:checkIfPossible()");
			return true;
		}
		
		public function compareWithSltn():Boolean
		{
			trace("ENTER:compareWithSltn()");
			var tempSolve:Array = service.GetSdkSolve();
			//trace(btn81, "-", tempSolve);
			if(btn81.every( function( x : *, index : int, arr :Array ) : Boolean 
				{ 
					trace("x.label", x.label, "index", index);
					return int(x.label) == tempSolve[index] 
				} ))
			{
				trace("EXIT:compareWithSltn()");
				return true;
			}
			trace("EXIT:compareWithSltn()");
			return false;
	
//			old school variant 
//			for(var ind:int = 0; ind < 81; ind++)
//			{
//				if (btn81[ind] != tempSolve[ind])
//				{
//					return false;
//				}
//			}
//			return true;
		}
		
		public function clickHandler(event:MouseEvent):void 
		{
			trace("ENTER:clickHandler()");
			Button( event.target ).label = String( (parseInt( Button( event.target ).label ) + 1 ) % 10);
			var temp:ColorTransform = new ColorTransform();
			if ( parseInt(Button( event.target ).label) > 0 )
			{
				//TODO: change with setStyle();
				temp.color = 0x005FF0;
				Button( event.target ).transform.colorTransform = temp;
			}
			else
			{
				Button( event.target ).transform.colorTransform = colouredBtn;
			}
			//Alert.show(Button( event.target ).label);

			if (!checkIfPossible(event))
			{
				//TODO: change with setStyle();
				temp.color = 0xff001e;
				Button( event.target ).transform.colorTransform = temp;
				//Alert.show("NOT POSSIBLE");
			}
			trace("EXIT:clickHandler()");
		}
		

		public function check(solve:Label,save:Button):void
		{
			if (compareWithSltn())
			{
				solve.text='Congratulations !!!';
				save.enabled=true;
				timeR.stop();
			}
			else
			{
				solve.text='Make up your mind :)';
			}
				
			
		}
		
		public function Generate81Buttons(cnt:HBox, check:Button):void
		{
			
			trace('Generate81Buttons_START');
			check.enabled=true;
			
			trace('Timer Created');
			timeR.addEventListener(TimerEvent.TIMER, onTimer);
			TimerReset();
			timeR.start();
			
			cnt.removeAllChildren();
			service.xmlParse();
			iTableCnt = cnt;
			service.addEventListener('SrvLoad', Generate81Btn);
			trace('Generate81Buttons_END');
		}
		public function Generate81Btn(event:Event):Array
		{
			trace('Generate81Btn_START');
			btn81 = new Array();
			var LabelsArr:Array = service.GetSudoku();
			var i:int;
			var vBox:VBox = new VBox();
			var rojo:ColorTransform = new ColorTransform();
			rojo.color = 0x0099CC;
			for(i = 0; i < 81; i++)
			{	
				
				btn81[i] = new Button();
				
				btn81[i].id = i;
				trace (int(LabelsArr[i]));
				btn81[i].label = int(LabelsArr[i]);
				
				
				if ( parseInt(btn81[i].label) > 0 )
				{
					Button(btn81[i]).transform.colorTransform = rojo;
					//Button(btn81[i]).alpha = 0;
					Button(btn81[i]).enabled = false;
				}
				
				btn81[i].addEventListener(MouseEvent.CLICK, clickHandler);
				if ( 0 == i % 9 )
				{
					iTableCnt.addChild(vBox);
					vBox = new VBox();
				}
				vBox.addChild(btn81[i]);
			}
			iTableCnt.addChild(vBox);
			return btn81;
			trace('Generate81Btn_END');
		}
	}
}